import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';

import '../../../../data/controllers/player_controller.dart';
import '../../../../data/models/auth/user.dart';
import '../../../../data/remote/database_helper.dart';

part 'players_tab_state.dart';
part 'players_tab_event.dart';

class PlayersTabCubit extends Bloc<PlayersTabEvent,PlayersTabState> {
  PlayersTabCubit(PlayersTabState playersTabInitial) : super(playersTabInitial) {
    on<PlayerTabInitialEvent>(_onInitialize);
    // for add player
    on<AddPlayerLoadingTapEvent>(_onAddPlayerLoading);
    on<AddPlayerFailedTapEvent>(_onAddPlayerFailed);
    on<AddPlayerSuccessTapEvent>(_onAddPlayerSuccess);
    // for update player
    on<UpdatePlayerLoadingEvent>(_onUpdatePlayerLoading);
    on<UpdatePlayerFailedEvent>(_onUpdatePlayerFailed);
    on<UpdatePlayerSuccessEvent>(_onUpdatePlayerSuccess);
    //for delete player
    on<DeletePlayerLoadingEvent>(_onDeletePlayerLoading);
    on<DeletePlayerFailedEvent>(_onDeletePlayerFailed);
    on<DeletePlayerSuccessEvent>(_onDeletePlayerSuccess);
    on<ChangeSelectMode>(_onChangeSelectMod);
    on<ChangeSelectedItem>(_onChangeSelectedItem);
    on<TabSelectAll>(_onTabSelectAll);
  }
  static PlayersTabCubit get(context) => BlocProvider.of(context);



  TextEditingController searchBox = TextEditingController();

  List<User> allUsers = [];
  List<User> selectedUsers = [];
  List<User> users = [];



  bool searchFlag = false;
  bool selectedMode = false;

  _onInitialize(
      PlayerTabInitialEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
    searchBox.clear();
    emit(PlayersTabLoading());
    await PlayerController.getMyPlayers().catchError((e){
      emit(PlayersTabError());
      return null;
    }).then((value)async{
      if(value != null && value.state) {
        users = List<User>.generate(value.data.length, (index) => User.fromJson(value.data[index]));
        allUsers = users.where((e)=>true).toList();
        localeMyData();
        emit(PlayersTabDone());
      }else if(value != null){
        var res = await DatabaseHelper.getAllUsers();
        users = List<User>.generate(res.length, (index) => User.fromJson(res[index]));
        allUsers = users.where((e)=>true).toList();
        emit(PlayersTabDone());
      }else{
        if (kDebugMode) {
          print('value is null');
        }
        emit(PlayersTabLoading());
        var res = await DatabaseHelper.getAllUsers();
        users = List<User>.generate(res.length, (index) => User.fromJson(res[index]));
        allUsers = users.where((e)=>true).toList();
        emit(PlayersTabDone());
      }
    });
  }
  _onAddPlayerSuccess(
      AddPlayerSuccessTapEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
    users.add(event.user);
    allUsers.add(event.user);
    emit(PlayersTabUpdate());
  }
  _onAddPlayerFailed(
      AddPlayerFailedTapEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
  }
  _onAddPlayerLoading(
      AddPlayerLoadingTapEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
    print("جاري اضافة لاعب");
  }

  _onUpdatePlayerSuccess(
      UpdatePlayerSuccessEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
    print("تم تحديث اللاعب ${users[0].fullName}");

    for(int i =0 ;i<users.length;i++){
      if(users[i].userId == event.user.userId){
        users[i]= event.user;
        print("تم تحديث اللاعب ${users[i].fullName}");
      }

    }
    emit(PlayersTabUpdate());
  }
  _onUpdatePlayerFailed(
      UpdatePlayerFailedEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
  }

  _onUpdatePlayerLoading(
      UpdatePlayerLoadingEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
    print("جاري تحديث لاعب");
  }
  _onDeletePlayerSuccess(
      DeletePlayerSuccessEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
    users.removeWhere((e)=>e.userId == event.userId);
    emit(PlayersTabUpdate());
  }
  _onDeletePlayerFailed(
      DeletePlayerFailedEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
  }
  _onDeletePlayerLoading(
      DeletePlayerLoadingEvent event,
      Emitter<PlayersTabState> emit,
      ) async {
    print("جاري تحديث لاعب");
  }
  _onChangeSelectMod(
      ChangeSelectMode event,
      Emitter<PlayersTabState> emit,
      ) async {
    selectedMode = event.mod;
    print(event.mod);
    emit(PlayersTabUpdate());
  }

  _onChangeSelectedItem(
      ChangeSelectedItem event,
      Emitter<PlayersTabState> emit,
      ) async {
    if(event.value){
      selectedUsers.add(event.user);
    }else{
      selectedUsers.remove(event.user);
    }
  }
  _onTabSelectAll(
      TabSelectAll event,
      Emitter<PlayersTabState> emit,
      ) async {
    if(event.value == true) {
      for (User user in users) {
        selectedUsers.add(user);
      }
    }else{
      for (User user in users) {
        selectedUsers.remove(user);
      }
    }
    emit(SelectAllPlayersState(value: event.value));
  }
  localeMyData()async{
    for(int i=0;i<allUsers.length;i++) {
      await DatabaseHelper.insertUser( allUsers[i].toJsonLocale()).then((value){

      }).catchError((e) {
        print("اللاعب موجود");
      });
    }
  }


  onSearchTap(){
    print(searchFlag);
    searchFlag = !searchFlag;
    emit(PlayersTabUpdate());
  }
  onSearch(String text){
    if(text.isEmpty){
      users = allUsers.where((e)=>true).toList();
    }else {
      users = allUsers.where(
            (element) =>
                element.fullName.contains(text) ||
                    element.username?.contains(text)==true,

      ).toList();
    }
    emit(PlayersTabUpdate());
  }

}
